﻿// 初始化过滤器，该脚本需要放置于datagrid-filter.js之前
$.fn.treegrid.defaults.nofilter = '清除筛选';
$.fn.treegrid.defaults.equal = '等于';
$.fn.treegrid.defaults.notequal = '不等于';

$.fn.treegrid.defaults.contains = '包含';
$.fn.treegrid.defaults.beginwith = '作为开头';
$.fn.treegrid.defaults.endwith = '作为结尾';

$.fn.treegrid.defaults.less = '小于';
$.fn.treegrid.defaults.lessorequal = '小于等于';
$.fn.treegrid.defaults.greater = '大于';
$.fn.treegrid.defaults.greaterorequal = '大于等于';

$.fn.treegrid.defaults.containsinarray = '包含';
$.fn.treegrid.defaults.equalinarray = '等于';
$.fn.treegrid.defaults.notequalinarray = '不等于';
$.fn.treegrid.defaults.exists = '存在';

$.fn.treegrid.defaults.clearfilters = '清空所有自定义筛选条件';
$.fn.treegrid.defaults.filterTips = '请输入查询条件';

var listGridHandler = function (inputData, binderName) {
   
    var me = this;
    var grid;
    var pagedata = (inputData) ? inputData : {};
    var metadata = (inputData) ? inputData.MetaData : {};
   
    var pageFilters;
    var isExporting = false;

    // 可编辑View列表接口
    this.formID = undefined;
    this.formName = undefined;

    // 不可编辑Summary报表接口
    this.isSummary = false;

    this.filterParam = undefined;

    // 是否允许筛选
    this.enableFilter = true;

    // 对外接口
    this.iFrozenColumns = new Array();
    this.iDefaultFilters = new Array();
    this.iForceFilters = new Array();
    this.iOnLoadSuccess = undefined;

    this.fAddPagerButtons = function (buttonList) {
        if (!amCommon.isArray(buttonList)) {
            return;
        }

        me.getPager().pagination({
            buttons: buttonList
        });
    };

    this.fUpdateForceFilter = function (fieldName, fieldValue) {
        for (var i = 0; i < me.iForceFilters.length; i++) {
            if (me.iForceFilters[i].field == fieldName) {
                me.iForceFilters[i].value = fieldValue;
                break;
            }
        }

    };

    this.getForceFilter = function (fieldName) {
        var result = undefined;
        for (var i = 0; i < me.iForceFilters.length; i++) {
            if (me.iForceFilters[i].field == fieldName) {
                result = me.iForceFilters[i].value;
                break;
            }
        }

        return result;
    }

    this.GetDefaultFilter = function (fieldName) {
        var result = undefined;
        for (var i = 0; i < me.iDefaultFilters.length; i++) {
            if (me.iDefaultFilters[i].field == fieldName) {
                result = me.iDefaultFilters[i].value;
                break;
            }
        }

        return result;
    }

    this.getFilter = function (fieldName) {
        var result = undefined;
        var rules = me.grid.datagrid('options').filterRules;
        for (var i = 0; i < rules.length; i++) {
            if (rules[i].field == fieldName) {
                result = rules[i].value;
                break;
            }
        }
        return result;
    }


    this.getPager = function () {
        return me.grid.treegrid('getPager');
    };

    this.getData = function () {
        return me.grid.treegrid('getData');
    };

    this.getEditUrl = function (recordID, taskID) {
        return '/Business/FormData/EditPage/' + recordID + '?FormID=' + me.formID + '&CurrentTaskID=' + taskID;
    };

    this.getViewUrl = function (recordID, taskID) {
        return '/Business/FormView/ViewPage/' + recordID + '?FormID=' + me.formID + '&CurrentTaskID=' + taskID;
    };

    this.getNewUrl = function () {
        return '/Business/FormData/NewPage?FormID=' + me.formID;
    };

    this.getDeleteUrl = function (idString) {
        return "/api/FormData/Del/" + idString + "?FormID=" + me.formID;
    };

    this.formatActionLink = function (value, row, index) {
        var result = '';

        if (me.getViewUrl) {
            result += '<a href="#" style="float:left" title="查看" onclick="' + binderName + '.showViewDialog(' + row._ID + ', ' + row._TaskID + ')"><div class="icon-page-view"></div></a>';
        }

        if (me.getEditUrl) {
            result += '<a href="#" style="float:left" title="编辑" onclick="' + binderName + '.showEditDialog(' + row._ID + ', ' + row._TaskID + ')"><div class="icon-page-edit"></div></a>';
        }

        if (me.getDeleteUrl) {
            result += '<a href="#" style="float:left" title="删除" onclick="' + binderName + '.showDeleteDialog(' + row._ID + ')"><div class="icon-page-delete"></div></a>';
        }

        return result;
    };

    this.formatProductLink = function (value, row, index) {
        var result = '';

        if (me.getViewUrl) {
          
            result += '<a href="#" style="float:left" title="查看类别下产品列表" onclick="' + binderName + '.showProManage(' + row.id + ', ' + row._TaskID + ', ' + index + ')"><div class="icon-page-splb"></div></a>';
        }

       

        return result;
    };

    this.formatCheckBoxLook = function (value, row, index) {
        var result = '';
        if (value == undefined) {
            result += " <input type='checkbox' id='formPowerLook" + row.id + "'  />";
        } else {
            if (value == 0) {
                result += " <input type='checkbox' id='formPowerLook" + row.id + "'  />";
            } else {
                result += " <input type='checkbox' id='formPowerLook" + row.id + "' checked='checked' />";
            }
        }

        return result;
    };
    this.formatCheckBoxEdit = function (value, row, index) {
        var result = '';
        if (value == undefined) {
            result += " <input type='checkbox' id='formPowerEdit" + row.id + "'  />";
        } else {
            if (value == 0) {
                result += " <input type='checkbox' id='formPowerEdit" + row.id + "'  />";
            } else {
                result += " <input type='checkbox' id='formPowerEdit" + row.id + "' checked='checked' />";
            }
        }

        return result;
    };
    this.formatCheckBoxDel = function (value, row, index) {
        var result = '';
        if (value == undefined) {
            result += " <input type='checkbox' id='formPowerDel" + row.id + "'  />";
        } else {
            if (value == 0) {
                result += " <input type='checkbox' id='formPowerDel" + row.id + "'  />";
            } else {
                result += " <input type='checkbox' id='formPowerDel" + row.id + "' checked='checked' />";
            }
        }

        return result;
    };
    this.formatPictureLink = function (value, row, index) {
        var pictures = '';
        if (value && value.length > 0) {
            for (var i = 0; i < value.length; i++) {
                if (value[i].Path) {
                    var path = String.prototype.resolveClientUrl(value[i].Path);
                    var picLink = '<a style="float: left" title="点击查看图片" target="_blank" href="' + path + '"><div class="icon-picture-button"></div></a>';
                    pictures += picLink;
                }
            }
        }
        return pictures;
    };

    this.formatPercent = function (value) {
        if (value) {
            value = Number(value);
            var widthPercent = value;
            if (widthPercent < 0) {
                widthPercent = 0;
            }

            var percent = '<div style="width:' + widthPercent + '%;" class="grid-cell-percent">' + value + '%' + '</div>';
            return percent;
        } else {
            return '';
        }
    };

    this.formatDisplayName = function (value, row, index, itemName) {
        var result = '';

        if (row && amCommon.notEmpty(itemName)) {
            var displayName = row['_DisplayName_' + itemName];
            if (amCommon.notEmpty(displayName)) {
                result = displayName;

                // 显示外键链接
                var metaData = metadata[itemName];
                if (metaData && metaData.DataTypeInfo == 'TypeSingleOneTableFK' && Number(value) > 0) {
                    result = '<a href="#" onclick="' + binderName + '.showForeighKeyViewDialog(' + metaData.ForeignTableID + ', ' + value + ')">' + result + '</a>';
                }
            }
        }
        return result;
    };

    this.showForeighKeyViewDialog = function (foreighKeyFormID, recordID) {
        window.exStopBubble();

        var url = '/Business/FormView/ViewPage/' + recordID + '?FormID=' + foreighKeyFormID;
        window.showBusinessForm(null, url);
    };

    this.addFilterOperator = function () {
        if ($.fn.treegrid.defaults.operators) {
            $.fn.treegrid.defaults.operators.containsinarray = {
                text: $.fn.treegrid.defaults.containsinarray,
                isMatch: function (source, value) {
                    if (source.contains) {
                        return source.contains(value);
                    }
                    else {
                        return false;
                    }
                }
            };
            $.fn.treegrid.defaults.operators.equalinarray = {
                text: $.fn.treegrid.defaults.equalinarray,
                isMatch: function (source, value) {
                    var matchResult = false;
                    if (source
                        && source.length == 1
                        && source[0] == value) {
                        matchResult = true;
                    }
                    return matchResult;
                }
            };
            $.fn.treegrid.defaults.operators.notequalinarray = {
                text: $.fn.treegrid.defaults.notequalinarray,
                isMatch: function (source, value) {
                    var matchResult = true;
                    if (source
                        && source.length == 1
                        && source[0] == value) {
                        matchResult = false;
                    }
                    return matchResult;
                }
            };
            $.fn.treegrid.defaults.operators.exists = {
                text: $.fn.treegrid.defaults.exists,
                isMatch: function (source, value) {
                    var exists = false;
                    if (source
                        && source.length >= 1) {
                        exists = true;
                    }
                    return (value == "有") ? exists : (!exists);
                }
            };
        }
    };

    function usageSingleSelection(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'SingleSelection'
            || usageSingleReferCopy(jqGrid)
            || usageSingleListFilter(jqGrid)) {
            return true;
        }
        return false;
    }

    function usageSingleListFilter(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'SingleListFilter') {
            return true;
        }
        return false;
    }

    function usageSingleReferCopy(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'SingleReferCopy') {
            return true;
        }
        return false;
    }

    function usageMultiReferCopy(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (exUsageType == 'MultiReferCopy') {
            return true;
        }
        return false;
    }

    function usageMultiSelection(jqGrid) {
        var exUsageType = jqGrid.attr('exUsageType');
        if (usageMultiReferCopy(jqGrid) || exUsageType == 'MultiSelection') {
            return true;
        }
        return false;
    }

    this.usageSelectionExceptFilter = function (jqGrid) {
        if (!usageSingleListFilter(jqGrid)
            && (usageSingleSelection(jqGrid) || usageMultiSelection(jqGrid))) {
            return true;
        }
        return false;
    }
     this.showProManage = function (recordID, taskID) {
        window.parent.window.MenuClickHrefEvent("/User/LBProduct/index?classid=" + recordID, "商品管理", "tabsChildContent_1");
    };
    this.showEditDialog = function (recordID, taskID) {
        window.exStopBubble();

        if (me.getEditUrl) {
            window.showBusinessForm("编辑" + me.formName, me.getEditUrl(recordID, taskID));
        }
       
    };

    this.showViewDialog = function (recordID, taskID) {
        window.exStopBubble();

        if (me.getViewUrl) {
            window.showBusinessForm("查看" + me.formName, me.getViewUrl(recordID, taskID));
        }
    };

    this.showDeleteDialog = function (recordID) {
        window.exStopBubble();
       
        if (!me.getDeleteUrl) {
            return;
        }

        var idString = '';
        if (recordID > 0) {
            idString = recordID;
        }
        else {
            var checkedRows = me.grid.treegrid('getChecked');
            if (!checkedRows || checkedRows.length <= 0) {
                $.messager.alert('提示', "请选择需要删除的记录！", 'info');
                return;
            }

            for (var i = 0; i < checkedRows.length; i++) {
              
                if (checkedRows[i].id == 0) {
                    $.messager.alert('提示', "开始状态不能被删除！", 'info');
                    return;
                }
                idString += checkedRows[i].id + ',';
            }
           
        }

        $.messager.confirm('删除确认', '确实要删除选中的记录？', function (r) {
            if (r) {
                $.ajax({
                    type: "POST",
                    url: me.getDeleteUrl(idString)
                })
                .success(function (result) {
                    if (result > 0) {
                        me.refreshGrid();
                    }
                    else if (result == -2) {
                        $.messager.alert('提示', "有其他资料引用该数据，禁止删除！", "error");
                    }
                    else {
                        $.messager.alert('提示', "有其他资料引用该数据，禁止删除！", "error");
                    }
                })
                .error(function (result) {
                    var message = "很抱歉，操作出现异常！请联系管理员。";
                    if (result) {
                        if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                            message = result.responseJSON.ExceptionMessage;
                        }
                        else if (result.responseText) {
                            message = result.responseText;
                        }
                    }

                    $.messager.alert('错误', message.replace("-10", ""), 'error');
                });
            }
        });
    };

    this.showReferDialog = function (referedTableID, referedTableName) {
        var newLayer = window.showBusinessDialog(referedTableID, referedTableName, null, null, null, 'SingleReferCopy');
        newLayer.showNewDialogByRefer = function (selectedRow) {
            // 关闭选择引用记录的对话框
            top.closeDialog();

            // 弹出以引用方式新建的对话框
            if (selectedRow && selectedRow._ID > 0 && me.getNewUrl) {
                var referUrl = me.getNewUrl() + '&ReferedTableID=' + referedTableID + '&ReferedRecordID=' + selectedRow._ID;
                window.showBusinessForm("新建" + me.formName, referUrl);
            }
        };
    };

    this.showCopyDialog = function () {
        var copyRecordID = getCopyRecordID();
        if (copyRecordID > 0 && me.getNewUrl) {
            var copyUrl = me.getNewUrl() + '&ReferedRecordID=' + copyRecordID;
            window.showBusinessForm("新建" + me.formName, copyUrl);
        }
    };

    this.showNewDialog = function () {
        if (me.getNewUrl) {
            window.showBusinessForm("新建" + me.formName, me.getNewUrl());
        }
    };

    this.refreshGrid = function () {
        if (me.grid) {
            me.grid.treegrid('reload');
        }
    };

    this.bindComboClear = function (element) {
        if (element == undefined) {
            element = this;
        }

        var comboClear = new comboClearFunction(element);
        comboClear.addClearButton();
    };

    function getCopyRecordID() {
        var checkedRows = me.grid.treegrid('getChecked');
        if (!checkedRows || checkedRows.length <= 0) {
            $.messager.alert('提示', "请选择一行需要复制的记录！", 'info');
            return -1;
        }

        if (checkedRows.length > 1) {
            $.messager.alert('提示', "请选择一行需要复制的记录，当前选择的行数过多！", 'info');
            return -1;
        }

        return checkedRows[0]._ID;
    }

    function onComboChange(element, value, filterOperator) {
        var item = null;
        if (element.className == 'tree') {
            item = $(element).tree('options').exItemName;
        }
        else {
            item = $(element).combo('options').exItemName;
        }

        if (element.exComboClear && element.exComboClear.showClearButton) {
            element.exComboClear.showClearButton(value);
        }

        if (item) {
            if (value == undefined || value == null || value.toString().length <= 0) {
                me.grid.treegrid('removeFilterRule', item);
            } else {
                me.grid.treegrid('addFilterRule', {
                    field: item,
                    op: filterOperator,
                    value: value
                });
            }
            me.grid.treegrid('doFilter');
            me.refreshGrid();
        }
    }

    function createComboField(itemName, filterOperator, type) {
        var field =
        {
            field: itemName,
            type: (type) ? type : 'combobox',
            options: {
                exItemName: itemName,
                editable: false,
                onSelect: function (record) {
                    var recordValue;
                    if (record) {
                        recordValue = record.value;
                    }
                    else {
                        recordValue = $(this).combo('getValue');
                    }
                    onComboChange(this, recordValue, filterOperator);
                },
                onChange: function (newValue, oldValue) {
                    if (newValue == undefined || newValue == null || newValue.toString().length <= 0) {
                        onComboChange(this, null, filterOperator);
                    }
                }
            }
        };

        return field;
    }

    function createComboTreeField(itemName, filterOperator) {
        var field =
        {
            field: itemName,
            type: 'combotree',
            options: {
                exItemName: itemName,
                editable: true,
                url: '/api/AuthorityDepartment/List?IsSelect=1',
                onChange: function (newValue, oldValue) {
                    onComboChange(this, newValue, filterOperator);
                },
                onInit: me.bindComboClear
            }
        };

        return field;
    }

    function updateParentSelectValue(oneceSelectedRows, isUnSelect, keepPopupWindow, allSelectedRows) {
        if (top.getLastLayer) {
            var lastLayer = top.getLastLayer();
            if (lastLayer && lastLayer.updatePopupSelectValue) {
                lastLayer.updatePopupSelectValue(oneceSelectedRows, isUnSelect, keepPopupWindow, allSelectedRows, pageFilters);
            }
        }
    }

    function parentShowNewDialogByRefer(selectedRow) {
        if (top.getLastLayer) {
            var lastLayer = top.getLastLayer();
            if (lastLayer && lastLayer.showNewDialogByRefer) {
                lastLayer.showNewDialogByRefer(selectedRow);
            }
        }
    }

    function isSingleSelect() {
        var singleSelect = (me.grid.attr('exSingleSelect') == "true");
        var singleSelection = usageSingleSelection(me.grid);
        var multiSelection = usageMultiSelection(me.grid);

        if (multiSelection) {
            singleSelect = false;
        }

        if (singleSelection) {
            singleSelect = true;
        }

        return singleSelect;
    }

    function bindGridEvent() {
        var options = me.grid.treegrid('options');
        var singleSelection = usageSingleSelection(me.grid);
        var multiSelection = usageMultiSelection(me.grid);
        if (multiSelection) {
            options.onSelect = function (rowIndex, rowData) {
                updateParentSelectValue([rowData], null, true);
            };

            options.onSelectAll = function (rows) {
                updateParentSelectValue(rows, null, true);
            };

            options.onUnselect = function (rowIndex, rowData) {
                updateParentSelectValue([rowData], true, true);
            };

            options.onUnselectAll = function (rows) {
                updateParentSelectValue(rows, true, true);
            };

            options.onLoadSuccess = function (data) {
                if (!data || !data.rows) {
                    return;
                }

                // 标识选中行
                $.each(data.rows, function (index, item) {
                    if (item._CheckRow == true) {
                        me.grid.treegrid('checkRow', index);
                    }
                });
            }
        }
        
        if (singleSelection || multiSelection) {
            if (usageSingleReferCopy(me.grid)) {
                options.onDblClickRow = function (rowIndex, rowData) {
                    parentShowNewDialogByRefer(rowData)
                };
            }
            else {
                
                me.grid.treegrid({
                    onDblClickRow: function (row) {
           
                                var lastLayer;
                                if (top.getLastLayer) {
                                    lastLayer = top.getLastLayer();
                                }
                                var id = row.id;
                                if (!isNaN(id) && id < 0) {
                                    id = id * -1;
                                }
                                var nodeData = { "_ID": id, "SystemName": row.text };
                                var selectedNodes = [nodeData];
                               
                                if (lastLayer != undefined) { 
                                    lastLayer.updatePopupSelectValue(selectedNodes);
                                }
                               // updatePopupSelectValue([row], null, null);

                            }
                        });
                //options.onDblClickRow = function (row) {
                //    alert("dd");
                //    alert(row);
                //   // updateParentSelectValue([rowData], null, null, [rowData]);
                //};
            }
        }
    }

    this.saveParentSelectValue = function () {
        var selectedRows = me.grid.treegrid('getSelections');
        updateParentSelectValue(null, null, null, selectedRows);
    }

    this.rejectParentSelectValue = function () {
        if (top.getLastLayer) {
            var lastLayer = top.getLastLayer();
            if (lastLayer && lastLayer.rejectSelectValue) {
                lastLayer.rejectSelectValue();
            }
        }
    }

    this.eventBeforeLoad = function (row, param) {
        pageFilters = undefined;
        if (!param) {
            if (!row) {
                return true;
            }
            else {
                param = row;
            }
        }

        // 加入上游传入的强制筛选参数
        param.exSelectIDs = pagedata.SelectIDs;
        var forceFilterArray = me.iForceFilters.concat();
        if (amCommon.notEmpty(pagedata.FilterItemName) && pagedata.FilterItemValue > 0) {
            forceFilterArray.push({
                field: pagedata.FilterItemName,
                op: 'equal',
                value: pagedata.FilterItemValue
            });
        }

        // 初始加载时加入各页自定义默认筛选条件
        if (me.iDefaultFilters && me.iDefaultFilters.length > 0) {
            param.filterRules = me.grid.datagrid('options').filterStringify(me.iDefaultFilters);
            me.iDefaultFilters = new Array();
        }

        // 加入各页自定义的强制筛选统计
        var addFilters = '';
        if (forceFilterArray && forceFilterArray.length > 0) {
            var forceFilters = me.grid.datagrid('options').filterStringify(forceFilterArray);
            if (amCommon.notEmpty(forceFilters)) {
                forceFilters = forceFilters.toString().trim('[').trim(']');
                if (amCommon.notEmpty(forceFilters)) {
                    addFilters += forceFilters + ',';
                }
            }
        }

        // 加入系统定义的强制筛选统计
        if (me.usageSelectionExceptFilter(me.grid)) {
            addFilters += amCommon.business.selectionFilter();
        }

        // 拼接筛选统计
        addFilters = addFilters.trimEnd(',');
        if (amCommon.notEmpty(addFilters)) {
            pageFilters = addFilters;
            if (!amCommon.notEmpty(param.filterRules)) {
                param.filterRules = '[' + addFilters + ']';
            }
            else {
                var orignalFilters = param.filterRules.toString().trim('[').trim(']');
                if (!amCommon.notEmpty(orignalFilters)) {
                    param.filterRules = '[' + addFilters + ']';
                } else {
                    pageFilters = orignalFilters + ',' + addFilters;
                    param.filterRules = '[' + pageFilters + ']';
                }
            }
        }

        me.filterParam = param;
    };

    this.eventLoadSuccess = function (gridData) {
        if (me.iOnLoadSuccess) {
            me.iOnLoadSuccess(gridData);
        }
    };

    this.bindFilter = function (jqGrid) {
        me.grid = jqGrid;
        me.addFilterOperator();
        var filterFields = [];
        for (var itemName in metadata) {

            var field = {
                field: itemName,
                type: 'validatebox',
                op: ['contains', 'equal', 'notequal', 'beginwith', 'endwith']
            };

            var metaData = metadata[itemName];
            switch (metaData.DataTypeInfo) {
                default:
                case 'TypeSinglelineText':
                case 'TypeMultilineText':
                    break;

                case 'TypeSingleSelect':
                case 'TypeFlowState':
                    field = createComboField(itemName, 'equal');
                    field.options.editable = true;
                    field.options.data = metaData.EnumValues;
                    field.options.onInit = me.bindComboClear;
                    break;

                case 'TypeMultiSelect':
                    field = createComboField(itemName, 'containsinarray');
                    field.options.editable = true;
                    field.options.data = metaData.EnumValues;
                    field.options.onInit = me.bindComboClear;
                    break;

                case 'TypeDatetime':
                    field = {
                        field: itemName,
                        type: 'datebox',
                        op: ['equal', 'notequal', 'greater', 'greaterorequal', 'less', 'lessorequal'],
                        options: { editable: false }
                    };
                    break;

                case 'TypeBoolean':
                    field = createComboField(itemName, 'equal');
                    field.options.data = [{ 'value': '1', 'text': '是' }, { 'value': '0', 'text': '否' }];
                    field.options.onInit = me.bindComboClear;
                    break;

                case 'TypeInteger':
                    field = {
                        field: itemName,
                        type: 'numberbox',
                        op: ['equal', 'notequal', 'greater', 'greaterorequal', 'less', 'lessorequal']
                    };
                    break;

                case 'TypeDecimal':
                    field = {
                        field: itemName,
                        type: 'numberbox',
                        options: { precision: metaData.DecimalLength },
                        op: ['equal', 'notequal', 'greater', 'greaterorequal', 'less', 'lessorequal']
                    };
                    break;

                case 'TypeSingleDepartment':
                    field = createComboTreeField(itemName, 'equal');
                    break;

                case 'TypeMultiDepartment':
                    field = createComboTreeField(itemName, 'containsinarray');
                    break;

                case 'TypeSingleUser':
                    field = createComboField(itemName, 'equal');
                    field.options.editable = true;
                    field.options.onInit = function () {
                        me.bindComboClear(this);
                        var comboTextButton = new comboTextButtonFunction(this);
                        comboTextButton.addTextButton();

                        var comboAutoComplete = new comboAutoCompleteFunction(this, this.exComboClear);
                        comboAutoComplete.userAutoComplete();
                    };
                    break;

                case 'TypeMultiUser':
                    field = createComboField(itemName, 'containsinarray');
                    field.options.editable = true;
                    field.options.onInit = function () {
                        me.bindComboClear(this);
                        var comboTextButton = new comboTextButtonFunction(this);
                        comboTextButton.addTextButton();

                        var comboAutoComplete = new comboAutoCompleteFunction(this, this.exComboClear);
                        comboAutoComplete.userAutoComplete();
                    };
                    break;

                case 'TypeMultiPicture':
                case 'TypeMultiAttachment':
                    field = createComboField(itemName, 'exists');
                    field.options.onInit = me.bindComboClear;
                    field.options.data = [{ 'value': '1', 'text': '有' }, { 'value': '0', 'text': '无' }];
                    break;

                case 'TypeSingleOneTableFK':
                case 'TypeSerialNumberCreationFK':
                case 'TypeSerialNumberSelectionFK':
                    field = createComboField(itemName, 'containsinarray');
                    field.options.editable = true;
                    field.options.onInit = function () {
                        me.bindComboClear(this);

                        var elementOptions = $(this).combo('options');
                        elementOptions.exUsageListFilter = true;

                        var item = elementOptions.exItemName;
                        var itemMeta = metadata[item];
                        var comboPopupSelect = new comboPopupSelectFunction(this,
                            itemMeta.ForeignTableID, '', itemMeta.ForeignTextItemName);
                        comboPopupSelect.addPopupSelect();

                        var comboAutoComplete = new comboAutoCompleteFunction(this, this.exComboClear);
                        comboAutoComplete.foreignKeyAutoComplete(itemMeta.ForeignTableID, itemMeta.ForeignTextItemName);
                    };
                    break;
            }

            filterFields.push(field);
        }

        //// 列排序
        //var fieldList = new Array();
        //var frozenFieldList = new Array();
        //var fieldContainer = jqGrid.find('thead[data-options!="frozen:true"] tr');
        //var frozenFieldContainer = jqGrid.find('thead[data-options="frozen:true"] tr');
        //for (var itemName in metadata) {
        //    var findField = fieldContainer.find('th[exField="' + itemName + '"]');
        //    if (findField.length > 0) {
        //        if (me.iFrozenColumns && me.iFrozenColumns.contains(itemName)) {
        //            frozenFieldList.push(findField);
        //        }
        //        else {
        //            fieldList.push(findField);
        //        }
        //    }
        //}

        //if (frozenFieldList.length > 0) {
        //    frozenFieldContainer.append(frozenFieldList);
        //}

        //fieldContainer.empty();
        //fieldContainer.append(fieldList);

        // 设置CheckBox列
        //if (isSingleSelect()) {
        //    frozenFieldContainer.find('th[exField="_CheckRow"]').remove();
        //}

        var defaultFilterRules = me.iDefaultFilters;
        var dataGrid = jqGrid.treegrid({
            onBeforeLoad: me.eventBeforeLoad,
            onLoadSuccess: me.eventLoadSuccess,
            onLoadError: function (result) {
                document.write(result.responseText);
            }
        });
        bindGridEvent();

        // 筛选条件
        if (me.enableFilter) {
            dataGrid.treegrid('enableFilter', filterFields);
            if (defaultFilterRules && defaultFilterRules.length > 0) {
                for (var i = 0; i < defaultFilterRules.length; i++) {
                    var filterRule = defaultFilterRules[i];
                    if (filterRule) {
                        dataGrid.treegrid('addFilterRule', filterRule);
                    }
                }
            }
        }

        var url = jqGrid.attr('exUrl');
        if (url) {
            dataGrid.treegrid('options').url = url;
        }
    };
  
    this.exportData = function () {
        if (!isExporting) {
            isExporting = true;

            var url = "/api/ImportExport/ExportData?FormID=" + me.formID;
            if (me.isSummary) {
                url = "/api/ImportExport/ExportReport?FormID=" + me.formID;
            }

            $.ajax({
                type: "POST",
                url: url,
                data: me.filterParam
            })
            .success(function (result) {
                if (result == 'false') {
                    $.messager.alert('提示', "很抱歉，操作出现异常！请联系管理员。", "error");
                }
                else {
                    var address = window.location;
                    window.open(address.protocol + '//' + address.host + result);
                }
                isExporting = false;
            })
            .error(function (result) {
                isExporting = false;
                $.messager.alert('提示', result.responseText, "error");
            });
        }
        else {
            $.messager.alert('提示', '正在导出文件...请稍等！', 'info');
        }
    };
}